package com.medeiros.upmoney.activity;

import java.io.Serializable;
import java.math.BigDecimal;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.ProgressBar;

import com.medeiros.upmoney.model.Limite;
import com.medeiros.upmoney.model.Status;
/**
 * Gastos: primeiro progresso
 * Valor: segundo progesso
 * @author Medeiros
 *
 */
public class LimiteView extends ProgressBar implements Serializable{
	private static final int BARRA_GASTO=2;
	private static final int BARRA_LIMITE = 1;
	private Limite limite;
	
	private int textColor = Color.BLACK;
	private float textSize = 15;

	public LimiteView(Limite limite, Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.limite = limite;
	}

	public void update(){
		this.setSecondaryProgress(limite.getPercentualValor().multiply(new BigDecimal(100)).intValue());
		this.setProgress(limite.getPercentualGasto().multiply(new BigDecimal(100)).intValue());
		updateColors();
	}
	private void updateText(Canvas canvas) {
		 Paint textPaint = new Paint();
		    textPaint.setAntiAlias(true);
		    textPaint.setColor(textColor);
		    textPaint.setTextSize(textSize);
		    //In order to show text in a middle, we need to know its size
		    Rect bounds = new Rect();
		    String text = getText();
			textPaint.getTextBounds(text, 0, text.length(), bounds);
		    //Now we store font size in bounds variable and can calculate it's position
		    int x = getWidth() / 2 - bounds.centerX();
		    int y = getHeight() / 2 - bounds.centerY();
		    //drawing text with appropriate color and size in the center
		    canvas.drawText(text, x, y, textPaint);
	}

	private String getText() {
		return this.getLimite().getTotalGasto().doubleValue() + "/" +this.getLimite().getValor().doubleValue();
	}

	private void updateColors() {
		LayerDrawable progressDrawable = (LayerDrawable) this.getProgressDrawable();
		int color = Status.findStatus(this.limite).getColor();
		
		Drawable bar = progressDrawable.getDrawable(BARRA_GASTO);
		bar.setColorFilter(color, Mode.SRC);
	}

	
	
	@Override  
	protected synchronized void onDraw(Canvas canvas) { 
		super.onDraw(canvas);  
		updateText(canvas);
		update();
	}  

	public Limite getLimite() {
		return limite;
	}

	public void setLimite(Limite limite) {
		this.limite = limite;
	}

	public void addGasto(float valor) {
		this.getLimite().addGasto(valor);
	}

}
